package com.kwin;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

import java.util.ArrayList;

/**
 * 不能连集群只能连多个单实例Redis,每个实例放部分数据
 */
public class ShardedPoolUtil {
    private static ShardedJedisPool jedisPool;
    public static ShardedJedisPool getJedisPool () {
        if (jedisPool == null) {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(200);
            config.setMaxIdle(200);
            config.setMaxWaitMillis(1000 * 100);
            config.setTestOnBorrow(false);
            ArrayList<JedisShardInfo> shardInfos = new ArrayList<JedisShardInfo>();
            shardInfos.add(new JedisShardInfo("127.0.0.1", 6379));
//            shardInfos.add(new JedisShardInfo("106.53.96.171", 6380));
//            shardInfos.add(new JedisShardInfo("106.53.96.171", 6381));
            jedisPool = new ShardedJedisPool(config, shardInfos);
        }
        return jedisPool;
    }

    public static void set (String key, String value) {
        ShardedJedisPool pool = null;
        ShardedJedis jedis = null;

        try {
            pool = getJedisPool();
            jedis = pool.getResource();
            jedis.set(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String get (String key) {
        String value = null;
        ShardedJedisPool pool = null;
        ShardedJedis jedis = null;
        try {
            pool = getJedisPool();
            jedis = pool.getResource();
            value = jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    public static void main(String[] args) {
        String age = "30";
        String address = "beijing";
        set("age", age);
        set("address", address);
        System.out.println(get("age"));
        System.out.println(get("address"));
    }
}
